package cn.com.demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.com.demo.constant.GlobalProperty;

public class ControllerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		String path = request.getRequestURI();
		// 循环不比过滤的连接 直接跳转出去
		for (int i = 0; i < GlobalProperty.ACCESS_URL.length; i++) {
			if (path.equals(GlobalProperty.ACCESS_URL[i].toString())) {
				return super.preHandle(request, response, handler);
			}
		}
		if (null == request.getSession().getAttribute(
				GlobalProperty.SESSION_USER)) {
			// session失效后 跳转登陆页面
			request.setAttribute("error", "没有登录系统或会话超时，请先登陆系统！");
			// /login
			request.getRequestDispatcher("/login.jsp").forward(request,
					response);
			return false;
		}

		return super.preHandle(request, response, handler);
	}

}
